/*
 * @Description: 
 * @Version: 1.0
 * @Author: wenbin
 * @Date: 2021-03-29 15:39:15
 * @LastEditors: wenbin
 * @LastEditTime: 2021-07-22 15:27:04
 * @FilePath: /magus-plugin/common/utils/common.js
 * Copyright (C) 2021 wenbin. All rights reserved.
 */

let commonUtils = {
  /**
   * @description: 深拷贝
   * @param {*} obj
   * @param {*} cache
   * @return {*}
   */
  deepCopy: function (obj, cache = []) {
    function find(list, f) {
      return list.filter(f)[0];
    }

    if (obj === null || typeof obj !== 'object') {
      return obj;
    }

    const hit = find(cache, c => c.original === obj);
    if (hit) {
      return hit.copy;
    }

    const copy = Array.isArray(obj) ? [] : {};
    cache.push({
      original: obj,
      copy
    });

    Object.keys(obj).forEach(key => {
      copy[key] = commonUtils.deepCopy(obj[key], cache);
    });

    return copy;
  },
  /**
   * @description: 给某个元素加class
   * @param {*} element
   * @param {*} className
   * @return {*}
   */
  toggleClass: function (element, className) {
    if (!element || !className) {
      return;
    }
    element.className = className;
  },

  /**
   * @description: 获取链接参数
   * @param {*} variable
   * @return {*}
   */
  getQueryVariable: function (variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if(pair[0] == variable){return pair[1];}
    }
    return(false);
  },

  /**
 * 对象转url参数
 * @param {*} data,对象
 * @param {*} isPrefix,是否自动加上"?"
 */
  queryParams: function (data = {}, isPrefix = true, arrayFormat = 'brackets') {
    let prefix = isPrefix ? '?' : ''
    let _result = []
    if (['indices', 'brackets', 'repeat', 'comma'].indexOf(arrayFormat) == -1) arrayFormat = 'brackets';
    for (let key in data) {
        let value = data[key]
        // 去掉为空的参数
        if (['', undefined, null].indexOf(value) >= 0) {
            continue;
        }
        // 如果值为数组，另行处理
        if (value.constructor === Array) {
            // e.g. {ids: [1, 2, 3]}
            switch (arrayFormat) {
                case 'indices':
                    // 结果: ids[0]=1&ids[1]=2&ids[2]=3
                    for (let i = 0; i < value.length; i++) {
                        _result.push(key + '[' + i + ']=' + value[i])
                    }
                    break;
                case 'brackets':
                    // 结果: ids[]=1&ids[]=2&ids[]=3
                    value.forEach(_value => {
                        _result.push(key + '[]=' + _value)
                    })
                    break;
                case 'repeat':
                    // 结果: ids=1&ids=2&ids=3
                    value.forEach(_value => {
                        _result.push(key + '=' + _value)
                    })
                    break;
                case 'comma': {
                  // 结果: ids=1,2,3
                  let commaStr = "";
                  value.forEach(_value => {
                      commaStr += (commaStr ? "," : "") + _value;
                  })
                  _result.push(key + '=' + commaStr)
                  break;
                }
                default:
                    value.forEach(_value => {
                        _result.push(key + '[]=' + _value)
                    })
            }
        } else {
            _result.push(key + '=' + value)
        }
    }
    return _result.length ? prefix + _result.join('&') : ''
  },
  /**
   * @description: 通过code获取字典信息
   * @param {*}
   * @return {*}
   */  
  getDictionaryBycode: function (code) {
    let dictionary = localStorage.getItem("dictionary");
    let dictionaryData;
    if (dictionary) {
      let dictionaryCatch = JSON.parse(dictionary);
      let optionObj = dictionaryCatch.find((i) => i.code === code);
      if (optionObj) {
        dictionaryData = optionObj.items;
      } else {
        dictionaryData = [];
      }
    } else {
      dictionaryData = [];
    }
    return dictionaryData;
  },
  /**
   * @description: 查询字典项的值
   * @param {*} code 字典code
   * @param {*} value 通过哪个值查询
   * @param {*} showType 展示的类型
   * @param {*} findType 查询的类型
   * @return {*}
   */  
  getDictLabel: function (code, value, showType = 'name', findType='value') {
    let dictionary = localStorage.getItem("dictionary");
    let labelValue = "";
    if (dictionary) {
      let dictionaryCatch = JSON.parse(dictionary);
      let optionObj = dictionaryCatch.find((i) => i.code === code);
      if (optionObj && optionObj.items) {
        let optionObjItem = optionObj.items;
        let showData = optionObjItem.find(
          (i) => i[findType] === value
        );
        if (showData) {
          labelValue = showData[showType];
        }
      }
    }
    return labelValue
  },
  /**
   * @description: 通过参数code获取参数的值
   * @param {*} code
   * @return {*}
   */  
  getParamsValue: function(code) {
    let parameter = localStorage.getItem("parameter");
    let value = "";
    if(parameter) {
      let parameterCatch = JSON.parse(parameter);
      let optionObj = parameterCatch.find(i => i.code === code);
      if (optionObj && optionObj.value) {
        value = optionObj.value
      }
    }
    return value;
  }
}


export default commonUtils